// sender.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <time.h>
#include <string.h>

#define QUEUE_NAME  "/test_queue1"
#define MAX_SIZE    1024
#define MSG_STOP    "exit"

int main() {
    mqd_t mq;
    struct mq_attr attr;
    char buffer[MAX_SIZE];
    struct timespec start_time;

    // 设置消息队列属性
    attr.mq_flags = 0;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = MAX_SIZE;
    attr.mq_curmsgs = 0;

    // 创建消息队列
    mq = mq_open(QUEUE_NAME, O_CREAT | O_WRONLY, 0644, &attr);
    if (mq == -1) {
        perror("mq_open");
        exit(1);
    }

    printf("Enter messages to send (type 'exit' to stop):\n");

    while (1) {
        printf("> ");
        fgets(buffer, MAX_SIZE, stdin);
        buffer[strcspn(buffer, "\n")] = 0;

        // 记录发送时间
        clock_gettime(CLOCK_MONOTONIC, &start_time);

        if (mq_send(mq, (char *)&start_time, sizeof(start_time), 0) == -1) {
            perror("mq_send");
            continue;
        }

        if (mq_send(mq, buffer, MAX_SIZE, 0) == -1) {
            perror("mq_send");
            continue;
        }

        if (strcmp(buffer, MSG_STOP) == 0)
            break;
    }

    // 关闭消息队列
    if (mq_close(mq) == -1) {
        perror("mq_close");
        exit(1);
    }

    return 0;
}
